import global from '@/global';


const downloadAndOpen = (url: string) => {
    if (url) {
        // @ts-ignore
        uni.$u.http.download(url).then(resp => {
            if (resp.header['Content-Type'].includes('image/')) {
                uni.previewImage({
                    urls: [resp.tempFilePath],
                    current: 0,
                    success: function (res) {
                        console.log('图片预览成功');
                    },
                    fail: function (err) {
                        console.error('图片预览失败: ', err);
                    }
                });
            } else {
                //新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
                uni.openDocument({
                    filePath: resp.tempFilePath,
                    showMenu: true,
                    success: function (res) {
                        console.log('打开文档成功');
                    }
                });
            }

        }).catch(err => {
            console.log(err)
        })
    }
};

// url获取文件名
const getFileNameByUrl = (url: string) => {
    return url.split('/').pop();
};

// 获取文件json列表
const getFilesByJsonStr = (jsonStr: string) => {
    if (jsonStr) {
        const temp = JSON.parse(jsonStr);
        if (temp && temp.length > 0) {
            return temp.map((item: string) => {
                return global.baseUrl + item;
            });
        }
    }
    return []
};

// 获取json列表
const getListByJsonStr = (jsonStr: string) => {
    if (jsonStr) {
        return JSON.parse(jsonStr);
    }
    return []
};

// 获取一个元素
const getOneByArrIndex = (arr: any[], index: number): any => {
    // @ts-ignore
    if (uni.$u.test.array(arr)) {
        return arr[index];
    }
    return null;
};

const delay = (ms: number): Promise<void> => {
    return new Promise<void>(resolve => {
        setTimeout(resolve, ms);
    });
}

export {delay, getFileNameByUrl, getFilesByJsonStr, getListByJsonStr, getOneByArrIndex}
